<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.controller' );

class EcommerceController extends JController
{
	function display()
	{
		$user = & JFactory::getUser();
		if ( ($user->get('guest')) && (JRequest::getVar('layout') != "detail")) {
			JError::raiseError( 403, JText::_('Access Forbidden') );
			return;
		}		
		parent::display();
		if(!isset($_SESSION['cart']))
			$_SESSION['cart'] = array();
	}
	
	function addCart(){
		$db = &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
	
		$id = intval( JRequest::getVar('id') );
		$quantity = intval( JRequest::getVar('quantity') );
		
		if($id){
			$kt=0;
		
			for($i=1; $i<=intval($session->get('itemAmount')); $i ++ ){
				if($id == intval($session->get('id'.$i))){
					$kt=1;
					break;
				}
			}
			if($kt == 0){
				$query = "select * from #__pr_product where id = ". $id;
				$db->setQuery($query);
				$row = $db->loadObject();
				
				$itemAmount = intval($session->get('itemAmount'));
				$itemAmount = $itemAmount + 1 ;
				$session->set('itemAmount', $itemAmount);
		
				$i = intval($session->get('itemAmount'));
				$session->set('id'.$i, $row->id);
				$session->set('name'.$i, $row->name);
				$session->set('price'.$i, $row->price);
				$session->set('quantity'.$i, $quantity);
				
				$query = "INSERT INTO #__pr_session_cart(user_id, product_id, product_name, product_price, product_quantity) VALUES (".$user->id.", ".$row->id.", '".$row->name."', ".$row->price.", ".$quantity.")";
				$db->setQuery($query);
				$db->query();
			} else {
				$quantity1 = $session->get('quantity'.$i) + $quantity;
				$session->set('quantity'.$i, $quantity1);
				
				$query = "UPDATE #__pr_session_cart SET product_quantity = ".$quantity1." WHERE product_id = ".$id." AND user_id = ".$user->id;
				$db->setQuery($query);
				$db->query();
			}
			
			echo 1;
			exit;
		}
		echo 0;
		exit;
	}
	
	function addOrderCart(){
		$db = &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
	
		$arrId = JRequest::getVar('id');
		$arrQuantity = JRequest::getVar('quantity');
		
		for($y = 0; $y<count($arrId); $y++){
			$kt=0;
		
			for($i=1; $i<=intval($session->get('itemAmount')); $i ++ ){
				if($arrId[$y] == intval($session->get('id'.$i))){
					$kt=1;
					break;
				}
			}
			if($kt == 0){
				$query = "SELECT * FROM #__pr_product where id = ". $arrId[$y];
				$db->setQuery($query);
				$row = $db->loadObject();
				
				$itemAmount = intval($session->get('itemAmount'));
				$itemAmount = $itemAmount + 1 ;
				$session->set('itemAmount', $itemAmount);
		
				$i = intval($session->get('itemAmount'));
				$session->set('id'.$i, $row->id);
				$session->set('name'.$i, $row->name);
				$session->set('price'.$i, $row->price);
				$session->set('quantity'.$i, $arrQuantity[$y]);
				
				$query = "INSERT INTO #__pr_session_cart(user_id, product_id, product_name, product_price, product_quantity) VALUES (".$user->id.", ".$row->id.", '".$row->name."', ".$row->price.", ".$arrQuantity[$y].")";
				$db->setQuery($query);
				$db->query();
			} else {
				$quantity = $session->get('quantity'.$i) + $arrQuantity[$y];
				$session->set('quantity'.$i, $quantity);
				
				$query = "UPDATE #__pr_session_cart SET product_quantity = ".$quantity." WHERE product_id = ".$id." AND user_id = ".$user->id;
				$db->setQuery($query);
				$db->query();
			}
		}
		echo 1;
		exit;
	}
	
	function loadCart(){
		$db = &JFactory::getDBO();
		$session =& JFactory::getSession();
		$html = "";
		for($i = 1; $i <= $session->get('itemAmount'); $i++){
			$query = "select id, name, price FROM #__pr_product WHERE id = ".$session->get('id'.$i);
			$db->setQuery($query);
			$item = $db->loadObject();
			$html .= '<div class="eachCart">                        		
                    <p class="eachCart-name">'.$session->get('name'.$i).'</p>
					<input type="hidden" id="idRemove'.$session->get('id'.$i).'" name="idRemove'.$session->get('id'.$i).'" value="'.$session->get('id'.$i).'" />
                    <a class="eachClose" href="javascript:void(0);"></a>
                    <div class="eachCart-box clear-fix">
                        <p class="eachCart-value">Pris: '.$session->get('price'.$i).' kr</p>
                        <div class="eachCart-quantity clear-fix">
                            <a class="btnDown">Down</a>
                            <input class="inputSoluong" type="text" value="'.$session->get('quantity'.$i).'" />
                            <a class="btnUp">Up</a>
							<input type="hidden" value="'.$session->get('id'.$i).'" />
							<a class="btnRefresh">Refresh</a>
                        </div>
                    </div>                        		
                </div>';
		}
		echo $html;
		exit;
	}
	
	function loadLittleCart(){
		$db = &JFactory::getDBO();
		$session =& JFactory::getSession();
		
		$moneyTotal = 0;
		for($i = 1; $i <= $session->get('itemAmount'); $i++){
			$moneyToTal += ($session->get('price'.$i)*$session->get('quantity'.$i));
		}
		if($session->get('itemAmount')) $itemAmount = $session->get('itemAmount'); 
		else $itemAmount = 0;
		
		$html = "<p>Antal varer: ".$itemAmount."</p>
            <p>Total beløb: ".number_format($moneyToTal,0,',','.')." DKK</p>";
			
		echo $html;
		exit;
	}
	
	function deleteItem(){
		$session =& JFactory::getSession();
	
		for ($i= intval(JRequest::getVar('i')); $i< intval($session->get('itemAmount')); $i++){
			$j = $i + 1;
			$session->set('id'.$i, $session->get('id'.$j));
			$session->set('name'.$i, $session->get('name'.$j));
			$session->set('quantity'.$i, $session->get('quantity'.$j));
			$session->set('price'.$i, $session->get('price'.$j));
		}
		$current_tongsl = intval($session->get('itemAmount')) - 1;
		$session->set('itemAmount', $current_tongsl);
	
		echo 1;
		exit;
	}
	
	function updateCart(){
		$session =& JFactory::getSession();
		$id = intval( JRequest::getVar('id') );
		$quantity = intval( JRequest::getVar('quantity') );
		for ($i=1; $i<=intval($session->get('itemAmount')); $i++){
			if($session->get('id'.$i) == $id){
				$session->set('quantity'.$i , $quantity);
			}
		}
		echo 1;
		exit;
	}
	
	function checkOut(){
		
		$model = $this->getModel('list');
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
		$comment = JRequest::getVar('comment');
		$finishDate = strftime("%Y-%m-%d %H:%M:%S",strtotime(JRequest::getVar('finishDate')));
		$sendorder = JRequest::getVar('sendorder','0','int');
		
		$cart = array();
		if(!empty($_SESSION["cart"])){
			$cart = $_SESSION["cart"];
		}
		if(count($cart)){
			$db->setQuery("START TRANSACTION");
			$db->query();
			$query = "INSERT INTO #__pr_orders (order_date, order_user_id, order_status, order_comment, order_finished) value('".date('YmdHis')."' ,".$user->id.", 0, '".$comment."', '".$finishDate."')";
			//echo $query . "<br />";
			$db->setQuery($query);
			$result1 = $db->query();
			$order_id = $db->insertid();
			$order_total=0;
			$amount = count($cart);
			for($i=0 ; $i<count($cart); $i++)
			{
				$category_id = $cart[$i]['category_id'];
				$product_id = $cart[$i]['product_id'] ;
				$product_type = $cart[$i]['producttype_id'] ;
				$productdetail_id = (int)$model->getProductdetailId($category_id,$product_id,$product_type);
				$price = (int) $model->getPriceById($category_id,$product_id,$product_type);
				$order_total+= $price; 
				$query_customer = "INSERT INTO #__pr_cart(order_id, productdetail_id ) 
									VALUE ($order_id, $productdetail_id)";
				//echo $query_customer . "<br />";
				$db->setQuery($query_customer);
				$result2 = $db->query();
				if(!$result2)
					break;
			}
			$query = "UPDATE #__pr_orders SET order_total = $order_total, order_amount = $amount WHERE order_id = $order_id ";
			//echo $query . "<br />";
			$db->setQuery($query);
			$result3 = $db->query();
			if($result1 && $result2 && $result3)
			{
			   // echo "OK";
				$db->setQuery("COMMIT");			    
			    $db->query();			    
			}
			else
			{
			   // echo "NOT OK";
			    //var_dump($result1);
			    //var_dump($result2);
			    //var_dump($result3);
				$db->setQuery("ROLLBACK");
			    $db->query();
			}
			//exit;
			$db->setQuery("SELECT email FROM #__users WHERE id = 62");
			$admin_email = $db->loadResult();
			
			if($sendorder){
				if($this->sendEmail($order_id, $user->email, $admin_email)){
					unset($_SESSION['cart']);
					/* $query = "DELETE FROM #__pr_session_cart WHERE user_id = ".$user->id;
					$db->setQuery($query);
					$db->query(); */
					$this->setRedirect("index.php?option=com_ecommerce&view=orders&Itemid=24");
				} else {
					$this->setRedirect("index.php?option=com_ecommerce&view=list&Itemid=24&sendmail=0",'Kan ikke sende mails');
				}
			}else{
				unset($_SESSION['cart']);
				$this->setRedirect("index.php?option=com_ecommerce&view=orders&Itemid=24");
			}
		}
	}
	
	function sendMyEmail(){
		$user = & JFactory::getUser();
		$order_id = JRequest::getVar('order_id');
		if($this->sendEmail($order_id, $user->email)){
			$this->setRedirect("index.php?option=com_ecommerce&view=overall&Itemid=18",'Ordrer er blevet sendt til din e-mail');
		} else {
			$this->setRedirect("index.php?option=com_ecommerce&view=list&Itemid=16",'Kan ikke sende mails');
		}
	}
	
	function sendEmail($order_id, $to, $cc = ''){
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		
		$query = "SELECT * FROM #__users_extension WHERE id = ".$user->id;
		$db->setQuery($query);
		$user_info = $db->loadObject();
		
		$mail = new JConfig();
		$from = $mail->mailfrom;

		$subject = $mail->fromname.' - Bekendtgørelse nr. '.str_pad($order_id,6,"0",STR_PAD_LEFT).' af '.$user->name;
		
		$query = "SELECT order_date, order_finished, order_comment FROM #__pr_orders WHERE order_id = ".$order_id;
		$db->setQuery($query);
		$order_info = $db->loadObject();
		$order_text = str_pad($order_id,6,"0",STR_PAD_LEFT);
		$body = '
			<body style="font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; ">

<table style="width:780px; margin:0px auto; padding:10px;" width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><a style=" background:url('.JURI::base().'templates/bookrengoring/img/sggroup_logo.png) no-repeat; text-indent:-9999px; width:180px; height:93px; display:block; ">'.$mail->fromname.'</a></td>
  </tr>
  <tr>
  	<td colspan="1">
    	<table width="780px" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td style="background-color:#5D9ECA; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="2" >Faktura</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Faktura nummer:</td>
            <td width="467" style="color:#323232; font-size:12px; padding:1px;">'.$order_text.'</td>
          </tr>
		  <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Bestil dato</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.strftime('%d-%m-%Y', strtotime($order_info->order_date)).'</td>
          </tr>
		   
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Udførelses dato:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.strftime('%d-%m-%Y %H:%M:%S', strtotime($order_info->order_finished)).'</td>
          </tr>
		   
          <tr>
            <td style="background-color:#5D9ECA; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="2" >Kundeinformation</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Firma/institution:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->company.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Kontaktperson:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user->name.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Adresse:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->address.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Postnr.:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->post.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">By:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->city.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Telefon/mobil:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->phone.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">CVR-nr.:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->cvr.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">E-mail:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user->email.'</td>
          </tr>
		  <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Kommentar:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$order_info->order_comment.'</td>
          </tr>		 
       </table>
    </td>
  </tr>
  <tr>
  	<td style="border-bottom: 1px solid #5D9ECA;">
  		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
	            <td style="background-color:#5D9ECA; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="5" >Ordrelinier</td>
	        </tr>
			<tr>		       	
		       
		       	<td width="70" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Floor</td>
		       	<td width="400" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Navn værelse</td>
		       	<td width="60" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Kvalitet</td>
                <td width="100" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Pris (DKK)</td>
		    </tr>
			';
			
			$db->setQuery("SELECT order_total FROM #__pr_orders WHERE order_id = ".$order_id);
			$order_total = $db->loadResult();
			$query = "SELECT cat.name AS catname, pp.name AS product_name, pt.name as ptype, pd.price
			FROM ((((#__pr_cart AS cart LEFT JOIN #__pr_productdetail AS pd ON cart.productdetail_id = pd.id)
			LEFT JOIN #__pr_product_category AS pc ON pd.product_category_id = pc.id)
			LEFT JOIN #__pr_producttype AS pt ON pt.id = pd.producttype_id)
			LEFT JOIN #__pr_product AS pp ON pc.product_id = pp.id)
			LEFT JOIN jos_pr_category AS cat ON cat.id = pc.category_id
			WHERE cart.order_id = ".$order_id;
			
			$query = $db->setQuery($query);
			$cart = $db->loadObjectList();
				
			foreach ($cart as $item) {
			//	$query = "SELECT number FROM #__pr_product WHERE id = ".$item->product_id;
			//	$query = $db->setQuery($query);
			//	$pro = $db->loadObject();
			
		    $body .= '
			<tr>
		     
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->catname.'</td>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->product_name.'</td>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->ptype.'</td>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->price.' DKK</td>
		    </tr>';
			}
		
            $body .= '    
        </table>
  	</td>
  </tr>
  <tr>
  	<td style="text-align: right; color:#323232; font-size:12px; padding:0px; padding:2px 43px 50px 0; font-weight: bold;">At betale: '.$order_total.' DKK</td>
  </tr>
  <tr>
  	<td style="background-color:#5D9ECA; padding:1px; ">
  		<p style="color:#FFF; font-size:13px; margin:0;">Øresundsvej 12A - 2300 København S • CVR-nr. : 33 57 41 18 • Tlf.: 81 75 33 43 • rengoring@servicegroup.dk</p> 
  		<p style="color:#FFF; font-size:13px; margin:0;">Mail: <a onmouseover="this.style.textDecoration = \'underline\'" onmouseout="this.style.textDecoration = \'none\'" style="display:inline; text-decoration: none; color:#FFF;" href="mailto:rengoring@servicegroup.dk">rengoring@servicegroup.dk</a> - CVR-nr. : 33 57 41 18</p>
  	
	</td>
  </tr>
</table>
</body>
		';
		
		$message =& JFactory::getMailer();
		$message->IsHTML(true);
		$message->addRecipient($to);
		if($cc){
			$message->addCC($cc);
		}
		$message->setSubject($subject);
		$message->setBody($body);
		$sender = array( $from, $mail->sitename );
		$message->setSender($sender);
		$sent = $message->send();
		if($sent){
			return true;
		} else {
			return false;
		}
	}
	
	
	function exportPdf(){
		
		require_once("libraries/joomla/document/pdf/pdf.php");
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		
		$order_id = JRequest::getVar('order_id');
		
		$query = "SELECT * FROM #__users_extension WHERE id = ".$user->id;
		$db->setQuery($query);
		$user_info = $db->loadObject();
		
		$query = "SELECT order_date, order_comment FROM #__pr_orders WHERE order_id = ".$order_id;
		$db->setQuery($query);
		$order_info = $db->loadObject();
		$order_text = sprintf("%06d", $order_id);
		$body = '
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td><a href="index.php"><img src="images/imgLogo.jpg" width="150" /></a></td>
			  </tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td colspan="2" style="background-color:#5D9ECA; color:white;"><b>Faktura</b></td>
			  </tr>
			  <tr>
				<td width="309">Faktura nummer:</td>
				<td width="341">'.$order_text.'</td>
			  </tr>
			  <tr>
				<td width="309">Faktura dato:</td>
				<td width="341">'.date('d-m-Y', $order_info->order_date).'</td>
			  </tr>
			  <tr>
				<td width="309">Tidspunkt:</td>
				<td width="341">'.date('H:i:s', $order_info->order_date).'</td>
			  </tr>
			  <tr>
				<td colspan="2" >&nbsp;</td>
			  </tr>
			  <tr>
				<td colspan="2" style="background-color:#5D9ECA; color:white;"><b>Kundeinformation</b></td>
			  </tr>
			  <tr>
				<td width="309">Firma/institution:</td>
				<td width="341">'.$user_info->company.'</td>
			  </tr>
			  <tr>
				<td width="309">Kontaktperson:</td>
				<td width="341">'.$user->name.'</td>
			  </tr>
			  <tr>
				<td width="309">Adresse:</td>
				<td width="341">'.$user_info->address.'</td>
			  </tr>
			  <tr>
				<td width="309">Postnr.:</td>
				<td width="341">'.$user_info->post.'</td>
			  </tr>
			  <tr>
				<td width="309">By:</td>
				<td width="341">'.$user_info->city.'</td>
			  </tr>
			  <tr>
				<td width="309">Telefon/mobil:</td>
				<td width="341">'.$user_info->phone.'</td>
			  </tr>
			  <tr>
				<td width="309">CVR-nr.:</td>
				<td width="341">'.$user_info->cvr.'</td>
			  </tr>
			  <tr>
				<td width="309">E-mail:</td>
				<td width="341">'.$user->email.'</td>
			  </tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td>&nbsp;</td>
				  </tr>
				<tr>
					<td style="background-color:#5D9ECA; color:white;" width="650"><b>Ordrelinier</b></td>
				</tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td width="100">Varenr</td>
					<td width="250">Varenavn</td>
					<td width="100">Pris/enhed</td>
					<td width="80">Antal</td>
					<td width="120">Subtotal</td>
				</tr>
				<tr><td colspan="5">&nbsp;</td></tr>
			';
			$db->setQuery("SELECT order_total FROM #__pr_orders WHERE order_id = ".$order_id);
			$order_total = $db->loadResult();
			
			$query = "SELECT * FROM #__pr_cart WHERE order_id = ".$order_id;
			$query = $db->setQuery($query);
			$cart = $db->loadObjectList();
						
			foreach ($cart as $item) {
				$query = "SELECT number FROM #__pr_product WHERE id = ".$item->product_id;
				$query = $db->setQuery($query);
				$pro = $db->loadObject();
		    $body .= '
			<tr>
				<td width="100" >'.$pro->number.'</td>
				<td width="250" >'.$item->product_name.'</td>
				<td width="100" >'.$item->price.' kr</td>
				<td width="80" >'.$item->quantity.'</td>
				<td width="120" >'.$item->price*$item->quantity.' kr</td>
			</tr>
			';
			}
            $body .= '
			<tr><td colspan="5" width="650"><hr></td></tr>
			</table>   
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
			  	<td width="650" style="text-align: right; color:#323232; font-size:12px; padding:0px; padding:2px 0px 20px 0; font-weight: bold;"><b>At betale: '.$order_total.' kr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>
			  </tr>
			  <tr>
				<td style="color:white; width:650px; background-color:#5D9ECA">Dansk Cafe Service - Vesterbrogade 74,3. sal - 1620 København V - Tlf: +45 26 80 88 11<br />Mail: post@danskcafeservice.dk - CVR: 30892968
				</td>
			  </tr>
			</table>
		';
		//$body = '<page style="font-family: freeserif"><br />'.nl2br($body).'</page>';
		require("html2pdf/html2pdf.class.php");
		$name = 'Faktura nr. '.$order_id.' '.date("d-m-Y");
		$file_name = $name.".pdf";
		$encoded_filename = urlencode($file_name);
		$encoded_filename = str_replace("+", "%20", $encoded_filename);
		$ua = $_SERVER["HTTP_USER_AGENT"];
		$pdf = new HTML2PDF('P', 'A4', 'da');
		$pdf->pdf->SetDisplayMode('real');
		//$pdf->SetFont('arial','',5);//print_r($pdf);exit;
		$pdf->WriteHTML($body);
		$pdf->Output('images/pdf/'.$name.'.pdf', 'F'); 
			
		$url = "/var/www/clients/client22/web140/web/images/pdf/".$file_name;
		//$url = "D:/xampp/htdocs/cafe/images/pdf/".$file_name;
		$handle = fopen($url, "r");
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		
		//header('Content-Disposition: attachment; filename='.$encoded_filename);
		if (preg_match("/MSIE/", $ua)) {
			header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		} else if (preg_match("/Firefox/", $ua)) {
			header('Content-Disposition: attachment; filename*="' . $file_name . '"');
		} else {
			header('Content-Disposition: attachment; filename="' . $file_name . '"');
		}
			
		header('Content-Transfer-Encoding: binary');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		header('Content-Length: ' . filesize($url));
		ob_clean();
		flush();
		readfile($url);
		fclose($handle);
		exit;
	}
	
	function getprice(){
		$producttype_id = JRequest::getInt("quality",0);
		$product_id = JRequest::getInt("product_id",0);
		$category_id = JRequest::getInt("category_id",0);
		$model = $this->getModel('list');
		$price = $model->getPriceById($category_id,$product_id,$producttype_id);
		echo $this->formatPrice($price);
		exit;
		
	}
	
	function formatPrice($number){
		$number = number_format($number,2,",","");
		return str_replace(",00", ",-", $number);
	}
	
	function getcart(){
		$producttype_id = JRequest::getInt("quality",0);
		$product_id = JRequest::getInt("product_id",0);
		$category_id = JRequest::getInt("category_id",0);
		$actions = JRequest::getInt("actions",0);
		$newproduct = array("category_id"=>$category_id, "product_id"=>$product_id, "producttype_id"=>$producttype_id);
		$cart = array();
		if(!empty($_SESSION["cart"])){
			$cart = $_SESSION["cart"];
		}		
		if($actions=="1"){
			array_push($cart,$newproduct);
		}else{
			foreach($cart as $key=>$value){
				if($value["category_id"]==$category_id && $value["product_id"]==$product_id && $value["producttype_id"]==$producttype_id){
					unset($cart[$key]);
					break;
				}
			}
		}
		
		$_SESSION["cart"]=$cart;
		$model = $this->getModel('list');
		$categorytotalprice = 0;
		foreach ($cart as $pro){
			$price = $model->getPriceById($pro["category_id"],$pro["product_id"],$pro["producttype_id"]);
			if($pro["category_id"] ==  $category_id){
				$categorytotalprice += $price;
			} 
		}
		
		echo $this->formatPrice($categorytotalprice);
		exit;
	}
	
	function gettotalprice(){
		$totalprice = 0;
		$cart = array();
		$model = $this->getModel('list');
		if(!empty($_SESSION["cart"])){
			$cart = $_SESSION["cart"];
		}
		foreach ($cart as $pro){
			$price = $model->getPriceById($pro["category_id"],$pro["product_id"],$pro["producttype_id"]);
			$totalprice += $price;
			 
		}
		
		echo $this->formatPrice($totalprice);
		exit;
	}
	
	function delsession(){
		unset($_SESSION["cart"]);
	}
	
	function paging(){
		if(!isset($_SESSION['cart'])){
			$_SESSION['cart'] = array();
		}
		//var_dump($_SESSION['cart']);
		$lim   = JRequest::getInt('limit',10);
		$lim0  = JRequest::getVar('limitstart', 0, '', 'int');
		$orders = JRequest::getVar('orders', '');
		$category_id = JRequest::getVar('category_id', 0,'int');
		$model = $this->getModel('list');
		$result = $model->getProductPaging($category_id,$lim,$lim0,$orders);		
		$listproduct = $result["data"];
		$link = $result["link"];
		$producttype = $model->getProducttype();
		$html = "";
		
		
		$html .= '<div class="title-bar">';
		$html .= '<h2>BESTIL STUEPLAN Rengøring</h2>';
		$html .= '<div class="navigator-bar fl-right">';
		$html .= '<div id="pagination'. $category_id .'" class="pagination" class="pager fl-right">';
		$html .= $link;
		$html .= '</div>';
		$html .= '<input type="hidden" name="categoryid'. $category_id.'" id="categoryid'. $category_id.'" value="' .$category_id .'"/>';
		$html .= '</div>';
		$html .= '<div class="sort fl-right">';
		$html .= '<label>Sortering</label>';
		$html .= '<select id="sortOrder'. $category_id .'" onchange="setPaging('.$category_id.')">';
		$html .= '<option value="ASC" ';
		if($orders=="ASC")
			$html .= 'selected="selected"';
		$html .= '>Diverse A - Z</option>';
		$html .= '<option value="DESC" ';
		if($orders=="DESC")
			$html .= 'selected="selected"';
		$html .= '>Diverse Z - A</option>';
		$html .= '</select>';
		$html .= '<label>Visning</label>';
		$html .= '<select id="viewNum'. $category_id .'" name="viewNum" class="viewNum" onchange="setPaging('.$category_id.')">';		
		if($lim==10){
			$html .= '<option value="10" selected="selected">10</option>';
		}else{
			$html .= '<option value="10">10</option>';
		}
		if($lim==20){
			$html .= '<option value="20" selected="selected">20</option>';
		}else{
			$html .= '<option value="20">20</option>';
		}
		if($lim==30){
			$html .= '<option value="30" selected="selected">30</option>';
		}else{
			$html .= '<option value="30">30</option>';
		}
		if($lim==0){
			$html .= '<option value="0" selected="selected">Alle</option>';
		}else{
			$html .= '<option value="0">Alle</option>';
		}
		$html .= '</select>';
		$html .= '</div>';
		$html .= '</div>';
		$html .= '<div class="table-list" id="table-list'. $category_id .'">';
		$html .= '<table class="order" cellpadding="0" cellspacing="0">';
		$html .= '<tbody>';
		$html .= '<tr class="first">';
		$html .= '<th width="450" class="left">Navn område</th>';
		$html .= '<th width="60">Kvalitet</th>';
		$html .= '<th>Vælg</th>';
		$html .= '<th width="148" class="right">Pris (DKK)</th>';
		$html .= '</tr>';
		
		$j=1;
		if(count($listproduct)){
			foreach($listproduct as $k=>$v):			
			$html .= '<tr';
			if($j%2==0){ 
				$html .= ' class="odd"';
			}else{
				$html .= ' class="even"';
			}
			
			$html .= '>';
			$html .= '<td class="area-name left">';
			$html .= $v->name;
			$html .= '</td>';
			$html .= '<td>';
			$html .= '<select class="quality-selector" id="quality' . $v->id . $category_id .'" onchange="getPrice(this,\''. $v->id .'\',\''.$category_id.'\')" onclick="checkactions(\''. $v->id.'\',\''. $category_id.'\');">';
			$arr_typeselected = array();
			foreach($producttype as $prot=>$type):
				$arr_search=array("category_id"=>$category_id,"product_id"=>$v->id,"producttype_id"=>$type->id);
				if(in_array($arr_search, $_SESSION['cart'])){
					array_push($arr_typeselected, $arr_search);
					$html .= '<option value="'. $type->id .'" selected="selected">'.$type->name.'</option>';
				}else{
					$html .= '<option value="'. $type->id.'">'.$type->name.'</option>';
				}
			endforeach;
			$html .= '</select>';														
			$html .= '</td>';
			$html .= '<td class="actions">';
			
			if($this->in_multi_array($arr_typeselected, $_SESSION['cart'])){
				$html .= '<input class="check-box" type="checkbox" value="1" id="actions'. $v->id . $category_id.'" onclick="updateproduct(\''.$v->id.'\',\''.$category_id.'\')" checked="checked" />';
			}else{
				$html .= '<input class="check-box" type="checkbox" value="1" id="actions'. $v->id . $category_id.'" onclick="updateproduct(\''.$v->id.'\',\''.$category_id. '\')" />';
			}
			
			$html .= '</td>';
			$html .= '<td width="148" class="price right">';
			$html .= '<span id="productprice'. $v->id . $category_id .'">';
			$typeselected = $this->gettypeselected($arr_typeselected, $category_id, $v->id);
			
			$price = $model->getPriceById($category_id, $v->id, $typeselected);
			
			$html .= $this->formatPrice($price);
			$html .= '</span>';
			$html .= '</td>';
			$html .= '</tr>';
				$j++;
				endforeach;
		}
		$html .= '<tr class="bottom">';
		$html .= '<td class="right" colspan="3">Subtotal på kategori "Stueplan" :</td>';
		$html .= '<td class="sub-total right"><span id="categorytotalprice'. $category_id.'">'. $model->gettotalPriceByCatid($category_id) . '</span></td>';
		$html .= '</tr>';
		$html .= '</tbody>';
	 	$html .= '</table>';
		echo $html;
		exit;
		
	}
	
	function in_multi_array($needle, $haystack)
	{
		$in_multi_array = false;
		if (in_array($needle, $haystack))
		{
			$in_multi_array = true;
		}else
		{
			foreach( $needle as $key1 => $val )
			{
				if(in_array($val, $haystack)){
					$in_multi_array = true;
				}
			}
		}
	
		return $in_multi_array;
	}
	
	function gettypeselected($needle, $catid, $product_id){
		foreach( $needle as $key1 => $val )
		{
			if($val["category_id"]==$catid && $val["product_id"]==$product_id){
				return $val["producttype_id"];
			}
		}
		return 1;
	}
	
	function getminicart(){
		$model = $this->getModel('list');
		$cart = array();
		if(!empty($_SESSION["cart"])){
			$cart = $_SESSION["cart"];
		}
		$totalprice = 0;
		foreach ($cart as $pro){
			$price = $model->getPriceById($pro["category_id"],$pro["product_id"],$pro["producttype_id"]);
			$totalprice += $price;
		}
		$html  = '<a class="bestil-info" href="#">';
		$html .= 'Antal ydelser : <strong>'.count($cart).'</strong> <br/>';
		$html .= 'Total beløb : <strong>'.$this->formatPrice($totalprice).' DKK</strong>';
		$html .= '</a>';
		echo $html;
		exit;
	}
}
?>